/**
 * Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 *
 * For the applicable distribution terms see the license.txt -file, included in
 * the distribution.
 */

#include <QApplication>

#include "purchasableitem.h"
#include "declarativepurchaselistmodel.h"
#include "CAFAPI/drmfile.h"

#define QMLICONRESOURCE_BUY "/qml/inapppurchase/content/icons/buy_protected.png"
#define QMLICONRESOURCE_NOTREADY "/qml/inapppurchase/content/icons/protected_notready.png"

PurchasableItem::PurchasableItem(DeclarativePurchaseListModel& model, QString& productID, QString& productUrl):
    PurchasableItemBase(model, productID, productUrl)
{
    m_productMetadata.drmProtection = IAPClient::OtherDrm;

    QString filepath = QApplication::applicationDirPath();

    m_buy_icon = new QImage(filepath + QMLICONRESOURCE_BUY);
    m_notready_icon = new QImage(filepath + QMLICONRESOURCE_NOTREADY);
}

void PurchasableItem::setUnlocked(QString* purchaseTicket)
{
    saveTicket(purchaseTicket);

    DRMFile file;
    int error = file.open(m_productUrl);
    //IMPORTANT NOTE: Access to unprotected content is unrestricted by CAF
    //thus the checking below will pass for ordinary non-protected files
    if(!error)
    {
        //DRM protected file is unlocked
        uchar* buffer;
        int len = file.read(buffer);
        if(len>0)
        {
            delete m_unlocked_icon;
            m_unlocked_icon = new QImage();
            m_unlocked_icon->loadFromData(buffer, len);  //keep allocated buffer in 'm_unlocked_icon'
        }
    }
    file.close();
}

bool PurchasableItem::isPurchased()
{
    return readTicket();
}
